<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑课程' : '新增课程' }}</span>
          <el-button @click="goBack" type="text">返回</el-button>
        </div>
      </template>

      <el-form ref="courseFormRef" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="课程名称" prop="title">
                  <el-input v-model="form.title" placeholder="请输入课程名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="课程编码" prop="code">
                  <el-input v-model="form.code" placeholder="请输入课程编码" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="课程分类" prop="categoryId">
                  <el-select v-model="form.categoryId" placeholder="请选择课程分类" style="width: 100%">
                    <el-option
                      v-for="category in categories"
                      :key="category.id"
                      :label="category.name"
                      :value="category.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="授课教师" prop="teacherId">
                  <el-select v-model="form.teacherId" placeholder="请选择授课教师" style="width: 100%">
                    <el-option
                      v-for="teacher in teachers"
                      :key="teacher.id"
                      :label="teacher.name"
                      :value="teacher.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="课程价格" prop="price">
                  <el-input-number v-model="form.price" :min="0" :precision="2" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="课程时长" prop="duration">
                  <el-input-number v-model="form.duration" :min="0" controls-position="right" style="width: 100%" />
                  <span style="margin-left: 8px;">分钟</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="难度等级" prop="level">
                  <el-select v-model="form.level" placeholder="请选择难度等级" style="width: 100%">
                    <el-option label="入门" value="BEGINNER" />
                    <el-option label="初级" value="ELEMENTARY" />
                    <el-option label="中级" value="INTERMEDIATE" />
                    <el-option label="高级" value="ADVANCED" />
                    <el-option label="专家" value="EXPERT" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="课程封面" prop="coverImage">
                  <el-upload
                    class="cover-uploader"
                    :action="uploadUrl"
                    :show-file-list="false"
                    :on-success="handleCoverSuccess"
                    :before-upload="beforeCoverUpload"
                  >
                    <img v-if="form.coverImage" :src="form.coverImage" class="cover-image" />
                    <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="课程简介" prop="summary">
                  <el-input
                    v-model="form.summary"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入课程简介"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="课程详情" prop="description">
                  <div ref="editorRef" style="height: 300px;"></div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 课程设置 -->
          <el-tab-pane label="课程设置" name="settings">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="课程状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio value="DRAFT">草稿</el-radio>
                    <el-radio value="PUBLISHED">已发布</el-radio>
                    <el-radio value="OFFLINE">已下架</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否免费" prop="isFree">
                  <el-radio-group v-model="form.isFree">
                    <el-radio :value="true">免费</el-radio>
                    <el-radio :value="false">付费</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否推荐" prop="isRecommended">
                  <el-switch v-model="form.isRecommended" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="允许试看" prop="allowPreview">
                  <el-switch v-model="form.allowPreview" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最大学员数" prop="maxStudents">
                  <el-input-number v-model="form.maxStudents" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序权重" prop="sort">
                  <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="课程标签" prop="tags">
                  <el-select
                    v-model="form.tags"
                    multiple
                    filterable
                    allow-create
                    placeholder="请选择或输入课程标签"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="tag in availableTags"
                      :key="tag"
                      :label="tag"
                      :value="tag"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="学习目标" prop="objectives">
                  <el-input
                    v-model="form.objectives"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入学习目标，每行一个"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="先修要求" prop="prerequisites">
                  <el-input
                    v-model="form.prerequisites"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入先修要求"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 时间设置 -->
          <el-tab-pane label="时间设置" name="schedule">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker
                    v-model="form.startTime"
                    type="datetime"
                    placeholder="请选择开始时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker
                    v-model="form.endTime"
                    type="datetime"
                    placeholder="请选择结束时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="报名开始" prop="enrollStartTime">
                  <el-date-picker
                    v-model="form.enrollStartTime"
                    type="datetime"
                    placeholder="请选择报名开始时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="报名结束" prop="enrollEndTime">
                  <el-date-picker
                    v-model="form.enrollEndTime"
                    type="datetime"
                    placeholder="请选择报名结束时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>

        <div style="margin-top: 20px; text-align: center;">
          <el-button type="primary" @click="submitForm" :loading="loading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getCourseDetail, 
  createCourse, 
  updateCourse, 
  getCourseCategories,
  getTeachers,
  getCourseTags
} from '@/api/classroom'

const route = useRoute()
const router = useRouter()

// 响应式数据
const courseFormRef = ref()
const editorRef = ref()
const loading = ref(false)
const activeTab = ref('basic')
const categories = ref([])
const teachers = ref([])
const availableTags = ref([])
const uploadUrl = ref('/api/upload/image')

// 富文本编辑器实例
let editor = null

// 表单数据
const form = reactive({
  id: undefined,
  title: '',
  code: '',
  categoryId: undefined,
  teacherId: undefined,
  price: 0,
  duration: 0,
  level: 'BEGINNER',
  coverImage: '',
  summary: '',
  description: '',
  status: 'DRAFT',
  isFree: true,
  isRecommended: false,
  allowPreview: true,
  maxStudents: 0,
  sort: 0,
  tags: [],
  objectives: '',
  prerequisites: '',
  startTime: null,
  endTime: null,
  enrollStartTime: null,
  enrollEndTime: null
})

// 计算属性
const isEdit = computed(() => !!route.params.id)

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入课程编码', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ],
  teacherId: [
    { required: true, message: '请选择授课教师', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ]
})

// 初始化富文本编辑器
const initEditor = async () => {
  // 这里可以集成富文本编辑器，如 Quill、TinyMCE 等
  // 示例代码，实际需要根据选择的编辑器进行配置
}

// 获取课程分类
const loadCategories = async () => {
  try {
    const response = await getCourseCategories()
    if (response.code === 200) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取课程分类失败:', error)
  }
}

// 获取教师列表
const loadTeachers = async () => {
  try {
    const response = await getTeachers()
    if (response.code === 200) {
      teachers.value = response.data
    }
  } catch (error) {
    console.error('获取教师列表失败:', error)
  }
}

// 获取课程标签
const loadTags = async () => {
  try {
    const response = await getCourseTags()
    if (response.code === 200) {
      availableTags.value = response.data
    }
  } catch (error) {
    console.error('获取课程标签失败:', error)
  }
}

// 获取课程详情
const loadCourseDetail = async () => {
  if (!isEdit.value) return
  
  try {
    const response = await getCourseDetail(route.params.id)
    if (response.code === 200) {
      Object.assign(form, response.data)
      // 处理日期格式
      if (form.startTime) form.startTime = new Date(form.startTime)
      if (form.endTime) form.endTime = new Date(form.endTime)
      if (form.enrollStartTime) form.enrollStartTime = new Date(form.enrollStartTime)
      if (form.enrollEndTime) form.enrollEndTime = new Date(form.enrollEndTime)
      
      // 设置编辑器内容
      if (editor && form.description) {
        editor.setContents(form.description)
      }
    }
  } catch (error) {
    console.error('获取课程详情失败:', error)
    ElMessage.error('获取课程详情失败')
  }
}

// 封面上传成功
const handleCoverSuccess = (response) => {
  if (response.code === 200) {
    form.coverImage = response.data.url
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error('封面上传失败')
  }
}

// 封面上传前验证
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
  }
  return isImage && isLt5M
}

// 提交表单
const submitForm = () => {
  courseFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 获取编辑器内容
        if (editor) {
          form.description = editor.getContents()
        }
        
        const formData = { ...form }
        // 处理日期格式
        if (formData.startTime) formData.startTime = formData.startTime.toISOString()
        if (formData.endTime) formData.endTime = formData.endTime.toISOString()
        if (formData.enrollStartTime) formData.enrollStartTime = formData.enrollStartTime.toISOString()
        if (formData.enrollEndTime) formData.enrollEndTime = formData.enrollEndTime.toISOString()
        
        if (isEdit.value) {
          await updateCourse(formData.id, formData)
          ElMessage.success('更新成功')
        } else {
          await createCourse(formData)
          ElMessage.success('创建成功')
        }
        goBack()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  courseFormRef.value?.resetFields()
  if (editor) {
    editor.setContents('')
  }
}

// 返回列表
const goBack = () => {
  router.push('/classroom/course')
}

// 页面加载
onMounted(async () => {
  await Promise.all([
    loadCategories(),
    loadTeachers(),
    loadTags(),
    initEditor()
  ])
  await loadCourseDetail()
})

// 页面卸载
onBeforeUnmount(() => {
  if (editor) {
    editor.destroy()
  }
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cover-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.cover-image {
  width: 200px;
  height: 120px;
  display: block;
  object-fit: cover;
}
</style>
